#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

void init(Stack_node *pstack)
{
    pstack->data=(char *)malloc(sizeof(char)*MAX_LEN);
    pstack->top=-1;
    pstack->capacity=MAX_LEN;
}

int get_size(Stack_node *pstack)
{
    return pstack->top+1;
}

char pop(Stack_node *pstack)
{
    if(pstack==NULL || pstack->data==NULL)
        return 0;
    char t=pstack->data[pstack->top];
    pstack->top--;
    return t;
}

int push(Stack_node *pstack, char element)
{
    if(pstack->data==NULL || pstack==NULL)
        return 0;
    if(need_expand(pstack))
        expand(pstack);
    pstack->top++;
    pstack->data[pstack->top]=element;
    return 1;
}


bool need_expand(Stack_node *pstack)
{
    if((pstack->capacity)-(pstack->top+1)<=5)
        return true;
    else
        return false;
}

void expand(Stack_node *pstack)
{
    pstack->capacity=pstack->capacity+MAX_LEN/2;
    pstack->data=(char *)malloc(sizeof(char)*pstack->capacity);
}


void clear(Stack_node *pstack)
{
    pstack->capacity=MAX_LEN;
    free(pstack->data);
    pstack->top=-1;
}

bool is_empty(Stack_node *pstack)
{
    if(pstack->top=-1)
        return true;
    else
        return false;
}


void delete_space1(char *str, int len)
{
    char *temp=(char *)malloc(sizeof(char)*len);
    int j=0;
    for(int i=0;i<len;i++)
    {
        if(!isspace(str[i]))
            temp[j++]=str[i];
    }
    for(int i=0;i<j;i++)
    {
        str[i]=temp[i];
    }
    free(temp);
    str[j]='\0';    // 添加结束标志
}


int judge(char ch)
{
    if(ch==')')
        return 1;
    else if(ch==']')
        return 2;
    else if(ch=='}')
        return 3;
    else
        return 0;
}

bool need_push(char ch)
{
    if(ch=='(' || ch=='[' || ch=='{')
        return true;
    else
        return false;
}

bool fun1(char ch1, char ch2)
{
    if(ch1==')'&&ch2=='(')
        return true;
    if(ch1==']'&& ch2=='[')
        return true;
    if(ch1=='}'&& ch2=='{')
        return true;
    return false;
}

bool parentheses_match(char *str, int len)
{
    printf("%s\n",str);
    if(str==NULL)
    {
        printf("您输入的字符串为空\n");
        return false;
    }
    Stack_node *pstack=(Stack_node *)malloc(sizeof(Stack_node));
    init(pstack);
    for(int i=0;i<len;i++)
    {
        if(need_push(str[i]))
            push(pstack,str[i]);
        if(judge(str[i]))
        {
            char t=pop(pstack);
            // printf("%c\n",t);
            if(!fun1(str[i],t))
                return false;
        }
    }
    if(!is_empty(pstack))
    {
        clear(pstack);
        return false;
    }
    return true;
    free(pstack);

}